package mylist
{
	import flash.display.Bitmap;
	import flash.display.Loader;
	import flash.events.Event;
	import flash.net.FileReference;
	import flash.utils.clearTimeout;
	import flash.utils.setTimeout;
	
	/**
	 * ...
	 * @author db0@qq.com
	 */
	public class Loaders
	{
		
		public function Loaders()
		{
			startLoad(true);
		}
		
		private static var index:int = 0;
		
		private static function startLoad(reset:Boolean = false):void
		{
			if (reset)
				index = 0;
			//logs.adds("index", index, FileItem.list.length);
			if (index < FileItem.list.length)
			{
				if (FileItem.list[index].state == "null")
				{ //未加载
					FileItem.list[index].state = FileItem.ADDSTAGE; //加载中
					FileItem.list[index].file.load();
					FileItem.list[index].file.addEventListener(Event.COMPLETE, loads);
				}
				else if (index < FileItem.list.length - 1)
				{
					++index;
					startLoad();
				}
			}
			else
			{
				logs.adds("all loaded");
			}
		}
		
		private static function loads(e:Event):void
		{
			if (FileItem.list[index].state == FileItem.ADDSTAGE)
			{
				FileItem.list[index].state = FileItem.ADDED;
				FileItem.list[index].jpeg = file.data;
				var file:FileReference = e.target as FileReference;
				var loader:Loader = new Loader();
				loader.contentLoaderInfo.addEventListener(Event.COMPLETE, addChilds);
				loader.loadBytes(file.data);
			}
			
		}
		
		static private function addChilds(e:Event):void
		{
			var bmp:Bitmap = e.target.content as Bitmap;
			ViewList.main.addChilds(bmp);
			waits();
		}
		
		static private var timeOut:uint;
		static private function waits():void
		{
			if (FileItem.list[index].state == FileItem.UPLOADED) {
				startLoad();
			}else {
				clearTimeout(timeOut);
				timeOut = setTimeout(waits, 100);
			}
		}
	}

}